import * as actionTypes from './constants';

const defaultstate = {
	selectGoods: [],  // 购物中数据初始状态
	isAllSelect: false, // 是否被全选
	isDelete: false  // 是否开启删除状态
}

const reducer = (state = defaultstate, action) => {
	switch (action.type) {
		case actionTypes.CHANGE_SELECTGOODS:
			// 深拷贝 先转成json字符串，再转成对象
			return {...state, selectGoods: JSON.parse(JSON.stringify([...state.selectGoods, action.data])),isAllSelect: false }
			// 只修改数据中的count 数量
		case actionTypes.CHANGE_SELECTGOODS_COUNT:
			let newGoods = state.selectGoods;
			newGoods[action.index].count++;
			return {...state, selectGoods: JSON.parse(JSON.stringify(newGoods))}
		case actionTypes.SETADD_COUNT:			
			let addGoodsCount = state.selectGoods;
			addGoodsCount[action.index].count++;
			return {...state, selectGoods: JSON.parse(JSON.stringify(addGoodsCount))}
		case actionTypes.SUBADD_COUNT:
			let subGoodsCount = state.selectGoods;
			subGoodsCount[action.index].count--;
			return {...state, selectGoods: JSON.parse(JSON.stringify(subGoodsCount))}
		case actionTypes.CHANGE_SELECT:
			let setSelect = state.selectGoods;
			setSelect[action.index].isSelect = !setSelect[action.index].isSelect;
			if(state.selectGoods.findIndex((item) => item.isSelect == false) == -1){
				state.isAllSelect = true
			}else {
				state.isAllSelect = false
			}
			return {...state, selectGoods: JSON.parse(JSON.stringify(setSelect)), isAllSelect: state.isAllSelect }
		case actionTypes.ALL_SELECT:
			let newSelect = state.selectGoods;
			if(state.isAllSelect && state.selectGoods.findIndex((item)=> item.isSelect == false) == -1){
				state.selectGoods.map((item) => {
					item.isSelect = false;
				})	
			}else{
				state.selectGoods.map((item) => {
					if(item.isSelect == false) {
						item.isSelect = !item.isSelect;
					}
				})
			
			}	
			return {...state, selectGoods: JSON.parse(JSON.stringify(newSelect)), isAllSelect: !state.isAllSelect}
		case actionTypes.DELETE_STATE:
			let newDelete = state.selectGoods;
			state.selectGoods.map((item) => {
				item.isSelect = false;
			})
			return {...state, selectGoods: JSON.parse(JSON.stringify(newDelete)), isAllSelect: false, isDelete: !state.isDelete}
		case actionTypes.DELETE_GOODS:
			let arr = []		
			state.selectGoods.map((item,index) => {
				if(item.isSelect == false){
					arr.push(state.selectGoods[index])
				}
			})
			return {...state, selectGoods: JSON.parse(JSON.stringify(arr))}
		default:
			return state
	}
}
export default reducer;